/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.renderer;

import com.jb.web.bean.FormField;
import com.jb.web.context.WebContext;

import java.text.SimpleDateFormat;

import java.util.Date;

import com.jb.faces.component.UIComponent;
import com.jb.faces.context.FacesContext;

public class DateFieldRenderer extends FormItemRenderer {
    public void decode(FacesContext pCtx, UIComponent item) {
        FormField formField = (FormField) item;
        WebContext ctx = (WebContext) pCtx;
        String fieldName = formField.getFieldName(ctx);
        String value = ctx.getRequest().getParameter(fieldName);

        if (isEmptyString(value)) {
            return;
        }

        if (formField.getMandatory() && ((value == null) || (value.length() == 0))) {
            ctx.addErrorMessage(formField, ctx.getResource("valueRequired") + " for " + this);
            pCtx.renderResponse();
        } else {
            String format = formField.getValueFormat();

            try {
                formField.setValue(value);

                Date date = new SimpleDateFormat(format).parse(value);
                formField.setDecodedValue(date);
            } catch (Exception e) {
                ctx.addErrorMessage(formField,
                    "Date value must be mm/dd/yyyy for " + fieldName + ".");
            //    ctx.renderResponse();
            }
        }
    }

    public StringBuffer render(WebContext pCtx, UIComponent itemToRender) {
        FormField formField = (FormField) itemToRender;
        StringBuffer html = new StringBuffer("");
        String fieldName = formField.getFieldName(pCtx);
        String dateString = "";

        Date date = (Date) formField.getModelBean();

        if (date == null) {
            date = (Date) evaluateObject(pCtx, formField, formField.getDefaultValue());
        }

        String format = formField.getValueFormat();

        if (isEmptyString(format)) {
            pCtx.addErrorMessage(formField, "valueFormat is expected");
        }

        if ((date != null) && (format != null)) {
            dateString = new SimpleDateFormat(format).format(date);
        }

        if (isVisible(pCtx, formField)) {
            html.append(textField(pCtx, formField, dateString));

            String PickerId = formField.getClientId(pCtx) + "PI";
            String id = PickerId + "Pos";

            if (!"none".equalsIgnoreCase(formField.getDisplayStyle())) {
                html.append("&nbsp;<img ")
                    .append(addTagProperty(" onmouseup",
                        "toggleDatePicker('" + PickerId + "','" + formField.getClientId(pCtx) + "')", null))
                    .append(addTagProperty(" id", id, null)).append(addTagProperty(" name", id, null))
                    .append(addTagProperty(" src", "resources/images/palette/cal.gif", null))
                    .append(addTagProperty(" align", "absmiddle", null)).append(addTagProperty(" border", "0", null))
                    .append(" />");
            }

            html.append(renderError(pCtx, formField));
        } else {
            html.append("<INPUT type =\"hidden\" name=\"" + fieldName + "\"")
                .append(addTagProperty(" value", dateString, null)).append(" />");
        }

        return html;
    }

    private StringBuffer textField(WebContext pCtx, FormField formField, String dateString) {
        StringBuffer html = new StringBuffer("");

        if ("0px".equalsIgnoreCase(formField.getWidth())) {
            formField.setWidth("10px");
        }

        String fieldName = formField.getFieldName(pCtx);
        html.append("<INPUT ").append(addTagProperty("name", fieldName, null)).append(addTagProperty(" type", "text",
                "text"));

        html.append(addTagProperty("size", formField.getWidth(), null)).append(addTagProperty("value", dateString, null))
            .append(addTagProperty("style", formField.getStyle(pCtx), null)).append(getEditScript(pCtx, formField))
            .append(" >&nbsp;</Input>");

        return html;
    }
}
